@page "/MySetting"
 

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Hosting
@using Microsoft.AspNetCore.Identity



@rendermode InteractiveServer
@attribute [Authorize]
@attribute [UserNavigation("个人设置")]
@attribute [TabItemOption(Text = "个人设置", Icon = "fa-solid fas fa-user-cog")]
 

      <ValidateForm Model="@userView" OnValidSubmit="OnValidSubmit2Async"> 
        <DataAnnotationsValidator />
        
                    <BootstrapInput @bind-Value="@userView.UserName"  Readonly    DisplayText="登录名"  />
           
                    <AvatarUpload @bind-Value="@userView.Icon" TValue="IBrowserFile" DisplayText="头像" Accept="jpg" OnDelete="OnDelete" DefaultFileList="@PreviewFileList" OnChange="@OnCardUpload" IsSingle="true" />
          
                    <BootstrapInput @bind-Value="@userView.DisplayName"   DisplayText="用户昵称"    />
                    <BootstrapInput @bind-Value="@userView.PhoneNubmbr"  DisplayText="手机号码"   type="number" />
                    <BootstrapInput @bind-Value="@userView.Email"  DisplayText="邮箱"   type="email" />
                    <Button ButtonType="@ButtonType.Submit" Text="提交"></Button>
        </ValidateForm>
 

<ValidateForm Model="@Input" OnValidSubmit="@OnValidSubmitAsync" >
    <DataAnnotationsValidator />
    
            <BootstrapInput @bind-Value="Input.OldPassword"   type="password"/>
            <BootstrapInput @bind-Value="Input.NewPassword" type="password"/>
            <BootstrapInput @bind-Value="Input.ConfirmPassword" type="password"/>
          
 

    <Button Color="Color.Primary" ButtonType="ButtonType.Submit">修改密码</Button>

</ValidateForm>

 
@code{

   [Inject]
    private IWebHostEnvironment? Environment { get; set; }
    public List<UploadFile> PreviewFileList { get; } = [];
 
 
    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();
    [Inject]
    [NotNull]
    private UserManager<User>? UserManager { get; set; }

   [Inject]
    [NotNull]
    private  NavigationManager? Navigation{ get; set; }
    private static long MaxFileLength => 5 * 1024 * 1024;
   [Inject]
    [NotNull]
    private SignInManager<User> SignInManager {get; set;}

    private CancellationTokenSource? ReadAvatarToken { get; set; }
    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }

    private UserVeiw userView = new UserVeiw();
     private User user =default;
      protected override async Task OnInitializedAsync()
    {
        user = await UserManager.GetUserAsync(SignInManager.Context.User);
        if (user == null)
        {
            throw new InvalidOperationException("Unable to load user.");
        }
        userView.UserName = user.UserName;
        userView.DisplayName = user.DisplayName;
        if (!string.IsNullOrEmpty(user.Icon))
        {
            var fileName = Path.GetFileName(user.Icon);
            if (!string.IsNullOrEmpty(fileName))
            {
            PreviewFileList.Add(new UploadFile()
            {
                Code = 0,
                FileCount = 1,
                FileName = fileName,
                PrevUrl = user.Icon
            });
            }
        }
    }
    private async Task OnValidSubmitAsync(EditContext editContext)
    {
        var changePasswordResult = await UserManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
        if (!changePasswordResult.Succeeded)
        {
            // 显示错误信息
            var errorMessage = string.Join(", ", changePasswordResult.Errors.Select(error => error.Description));
            await ToastService.Error("修改密码失败", errorMessage);
            return;
        }

        // 显示成功提示
        await ToastService.Success("修改密码成功", "请重新登录");
       
        // 使用 JavaScript 重定向到登录页面
        Navigation.NavigateTo($"Account/Logout?returnUrl={Uri.EscapeDataString(Navigation.Uri)}");
    }  


       private async Task OnValidSubmit2Async(EditContext editContext)
    {
      
        user.DisplayName = userView.DisplayName;
        user.Icon=  PreviewFileList.FirstOrDefault()?.PrevUrl;
        user.PhoneNumber = userView.PhoneNubmbr;
        user.Email = userView.Email;
        
        var result = await UserManager.UpdateAsync(user);
        if (result.Succeeded)
        {
            await ToastService.Success("头像上传成功", "请重新登录");
     
        }
        else
        {
            await ToastService.Error("头像上传失败", string.Join(", ", result.Errors.Select(e => e.Description)));
        }
    }  
    private static bool CheckValidAvatarFormat(string format)
    {
        return "jpg;png;bmp;gif;jpeg".Split(';').Any(f => format.Contains(f, StringComparison.OrdinalIgnoreCase));
    }

         private async Task OnCardUpload(UploadFile file)
    {
        if (file != null && file.File != null)
        {
            // 服务器端验证当文件大于 5MB 时提示文件太大信息
            if (file.Size > MaxFileLength)
            {
                await ToastService.Information("上传文件", "文件大小超过 5MB");
                file.Code = 1;
                file.Error = "文件大小超过 5MB";

            }
            else
            {
                await SaveToFile(file);
       
            }
        }
    }


      private async Task<bool> SaveToFile(UploadFile file)
    {
     

        var ret = false;
        if (!string.IsNullOrEmpty(Environment.WebRootPath))
        {
            var uploaderFolder = Path.Combine(Environment.WebRootPath, $"images{Path.DirectorySeparatorChar}avatars");
            file.FileName = $"{Path.GetFileNameWithoutExtension(file.OriginFileName)}-{DateTimeOffset.Now:yyyyMMddHHmmss}{Path.GetExtension(file.OriginFileName)}";
            var fileName = Path.Combine(uploaderFolder, file.FileName);

            ReadAvatarToken ??= new CancellationTokenSource();
            ret = await file.SaveToFileAsync(fileName, MaxFileLength, ReadAvatarToken.Token);

            if (ret)
            {

               
               
                // 保存成功
                file.PrevUrl = $"/images/avatars/{file.FileName}";
                PreviewFileList.Add(file);
            }
            else
            {
                var errorMessage = $"{"保存文件失败"} {file.OriginFileName}";
                file.Code = 1;
                file.Error = errorMessage;
                await ToastService.Error("上传文件", errorMessage);
            }
        }
        else
        {
            file.Code = 1;
            file.Error = "Wasm 模式未实现保存代码";
            await ToastService.Information("保存文件", "当前模式为 WebAssembly 模式，请调用 Webapi 模式保存文件到服务器端或数据库中");
        }
        return ret;
    }
    private  async Task<bool> OnDelete(UploadFile file)
    {
        // 删除文件
        if (file != null && file.File != null)
        {   
            if(file.Code==1)
            {
              return await Task.FromResult(true);
            }
            var uploaderFolder = Path.Combine(Environment.WebRootPath, $"images{Path.DirectorySeparatorChar}avatars");
            var fileName = Path.Combine(uploaderFolder, file.FileName);
            if (File.Exists(fileName))
            {   
                PreviewFileList.Remove(file);
                File.Delete(fileName);
            
                return true;
            }
        }

        return false;
    }
    


    private sealed class InputModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "旧密码")]
        public string OldPassword { get; set; } = "";

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "新密码")]
        public string NewPassword { get; set; } = "";

        [DataType(DataType.Password)]
        [Display(Name = "确认密码")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; } = "";
    }

    private sealed class UserVeiw
    {
        public string UserName { get; set; } = string.Empty;
        public string DisplayName { get; set; } = string.Empty;
        public IBrowserFile Icon { get; set; } = default!;
        [Phone]
        public string? PhoneNubmbr { get; set; } = string.Empty;

        [EmailAddress]
        [DataType(DataType.EmailAddress)]
        public string? Email { get; set; } = string.Empty;
    }
    
     

}